package com.example.function;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.adapter.StudentAdapter;
import com.example.database.DatabaseHelper;
import com.example.pojo.Student;
import com.example.student.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StudentFunction extends AppCompatActivity {
    // 下拉栏和学生列表相关组件
    private Spinner spinnerCollege, spinnerMajor, spinnerGrade;
    private RecyclerView recyclerViewStudents;
    private StudentAdapter studentAdapter;
    private DatabaseHelper databaseHelper;
    private List<Student> studentList = new ArrayList<>();
    // 学院和专业映射
    private Map<String, List<String>> collegeMajorMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_student_function);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化数据库
        databaseHelper = new DatabaseHelper(this);
        // 初始化视图
        initViews();
        // 初始化学院和专业数据
        initCollegeMajorData();
        // 初始化学生列表
        initStudentList();

        // 监听学院 Spinner 的选择事件
        spinnerCollege.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCollege = (String) parent.getItemAtPosition(position);
                updateMajorSpinner(selectedCollege);
                filterStudents();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 监听专业 Spinner 的选择事件
        spinnerMajor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                filterStudents();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        // 监听年级 Spinner 的选择事件
        spinnerGrade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                filterStudents();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 在 StudentFunctionActivity 或 StudentFunctionFragment 中
        FloatingActionButton fabAddStudent = findViewById(R.id.fab_add_student);
        fabAddStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 跳转到添加学生的表单页面
                Intent intent = new Intent(StudentFunction.this, AddStudent.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        filterStudents();
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        spinnerCollege = findViewById(R.id.spinnerCollege);
        spinnerMajor = findViewById(R.id.spinnerMajor);
        spinnerGrade = findViewById(R.id.spinnerGrade);
        recyclerViewStudents = findViewById(R.id.recyclerViewStudents);

        // 设置 RecyclerView
        recyclerViewStudents.setLayoutManager(new LinearLayoutManager(this));
        studentAdapter = new StudentAdapter(studentList, databaseHelper);
        recyclerViewStudents.setAdapter(studentAdapter);
    }

    /**
     * 初始化学院和专业数据
     */
    private void initCollegeMajorData() {
        collegeMajorMap = new HashMap<>();
        collegeMajorMap.put("计算机科学与技术", List.of("物联网工程", "计算机科学与技术", "网络安全"));
        collegeMajorMap.put("商学院", List.of("工商管理", "市场营销", "会计学"));
        collegeMajorMap.put("文学院", List.of("汉语言文学", "新闻学"));
        collegeMajorMap.put("理学院", List.of("数学与应用数学", "物理学", "化学"));
        collegeMajorMap.put("工程学院", List.of("机械工程", "电气工程", "土木工程"));
        collegeMajorMap.put("医学院", List.of("临床医学", "口腔医学", "药学"));
        collegeMajorMap.put("艺术学院", List.of("音乐学", "美术学", "设计学"));
        collegeMajorMap.put("法学院", List.of("法学", "知识产权", "国际法"));
        collegeMajorMap.put("教育学院", List.of("教育学", "心理学", "学前教育"));
        collegeMajorMap.put("农学院", List.of("农学", "园艺学", "植物保护"));
        // 初始化学院下拉框
        List<String> colleges = new ArrayList<>(collegeMajorMap.keySet());
        colleges.add(0, "请选择学院"); // 添加“请选择”选项
        ArrayAdapter<String> collegeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, colleges);
        collegeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCollege.setAdapter(collegeAdapter);

        // 初始化专业下拉框
        List<String> majors = new ArrayList<>();
        majors.add("请选择专业"); // 添加“请选择”选项
        ArrayAdapter<String> majorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, majors);
        majorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMajor.setAdapter(majorAdapter);

        // 初始化年级数据
        // 初始化年级下拉框
        List<String> grades = new ArrayList<>();
        grades.add("请选择年级"); // 添加“请选择”选项
        grades.addAll(List.of("21级", "22级", "23级", "24级"));
        ArrayAdapter<String> gradeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, grades);
        gradeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerGrade.setAdapter(gradeAdapter);

    }

    /**
     * 更新专业 Spinner 的内容
     */
    private void updateMajorSpinner(String college) {
        // 获取专业列表
        List<String> majors = collegeMajorMap.get(college);
        if (majors == null) {
            majors = new ArrayList<>(); // 如果 majors 为 null，使用空列表
        }

        // 添加“请选择专业”选项
        List<String> majorList = new ArrayList<>();
        majorList.add("请选择专业"); // 添加“请选择”选项
        majorList.addAll(majors);

        // 设置适配器
        ArrayAdapter<String> majorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, majorList);
        majorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMajor.setAdapter(majorAdapter);

        // 设置默认选中第一项
        if (majorAdapter.getCount() > 0) {
            spinnerMajor.setSelection(0);
        }
    }

    /**
     * 根据条件筛选学生
     */
    private void filterStudents() {
        // 获取选中的学院、专业和年级
        String college = spinnerCollege.getSelectedItem().toString() !="请选择学院" ? spinnerCollege.getSelectedItem().toString() : "";
        String major = spinnerMajor.getSelectedItem().toString() !="请选择专业"? spinnerMajor.getSelectedItem().toString() : "";
        String grade = spinnerGrade.getSelectedItem().toString() != "请选择年级" ? spinnerGrade.getSelectedItem().toString() : "";
        Log.d("aaa", "filterStudents: college:" + college + "major:" + major + "grade:" +grade);

        // 从数据库获取符合条件的学生
        studentList.clear();
        studentList.addAll(databaseHelper.getStudentsByFilter(college, major, grade));
        studentAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化学生列表
     */
    private void initStudentList() {
        // 从数据库获取所有学生
        studentList.clear();
        List<Student> students = databaseHelper.getAllStudents();
        studentList.addAll(students);
        studentAdapter.notifyDataSetChanged();
    }
}